package com.oa.srms.apps.dao.goods.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.oa.srms.apps.dao.goods.IGoodReceivedDao;
import com.oa.srms.apps.entity.goods.GoodReceivedValue;

public class GoodReceivedDaoImpl extends HibernateDaoSupport implements
		IGoodReceivedDao {
	@Autowired
	private List<GoodReceivedValue> list;
	
	@Override
	public Integer addGoodReceived(GoodReceivedValue goodReceivedValue)
			throws Exception {
		if (goodReceivedValue != null) {
			this.getHibernateTemplate().save(goodReceivedValue);
		}
		return goodReceivedValue.getId();
	}

	@Override
	public void editGoodReceived(GoodReceivedValue goodReceivedValue)
			throws Exception {
		if (goodReceivedValue != null) {
			this.getHibernateTemplate().update(goodReceivedValue);
		}
	}

	@Override
	public GoodReceivedValue queryById(Integer id) throws Exception {
		return (GoodReceivedValue) this.getHibernateTemplate().get(GoodReceivedValue.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<GoodReceivedValue> queryGoodReceived(final String stuNo, final Integer maxStates) throws Exception {
		String hqlStr = "SELECT grv FROM GoodReceivedValue grv, StudentInfoValue siv WHERE siv.id = grv.stuInfo.id";
		if(stuNo != null){
			hqlStr += " AND siv.stuNo = ?";
		}
		if(maxStates != null) {
			hqlStr += " AND (grv.states <= ?)";
		}
		final String hql = hqlStr;
		list = this.getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
				throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				int index = -1;
				if (stuNo != null) {
					query.setString(++index, stuNo);
				}
				if (maxStates != null) {
					query.setInteger(++index, maxStates);
				}
				list = query.list();
				return list;
			}
		});
		return list;
	}
}
